﻿#include "musicwindow.h"
#include "ui_musicwindow.h"


musicWindow::musicWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::musicWindow)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    QMovie *music_back=new QMovie(":/music_back.gif");
    ui->label->setMovie(music_back);
    ui->label->setStyleSheet("background:transparent");
    ui->label->setAttribute(Qt::WA_TransparentForMouseEvents);
    music_back->start();

    QIcon icon(":/music.png");
    ui->pushButton_2->setIcon(icon);
    ui->pushButton_2->setIconSize(ui->pushButton_2->size()); // 设置图标的尺寸
    ui->pushButton_2->setStyleSheet("border:none;background:none;");

    icon=QIcon(":/collectedSongs.png");
    ui->pushButton_6->setIcon(icon);
    ui->pushButton_6->setIconSize(ui->pushButton_6->size()); // 设置图标的尺寸

    icon=QIcon(":/music_search.png");
    ui->pushButton->setIcon(icon);
    ui->pushButton->setIconSize(ui->pushButton->size()); // 设置图标的尺寸
    ui->pushButton->setStyleSheet("border:none;background:none;");
    ui->pushButton->setShortcut(QKeySequence("Ctrl+l"));

    icon=QIcon(":/previous.png");
    ui->pushButton_3->setIcon(icon);
    ui->pushButton_3->setIconSize(ui->pushButton_3->size()); // 设置图标的尺寸
    ui->pushButton_3->setStyleSheet("border:none;background:none;");

    icon=QIcon(":/pause.png");
    ui->pushButton_4->setIcon(icon);
    ui->pushButton_4->setIconSize(ui->pushButton_4->size()); // 设置图标的尺寸
    ui->pushButton_4->setStyleSheet("border:none;background:none;");

    icon=QIcon(":/next.png");
    ui->pushButton_5->setIcon(icon);
    ui->pushButton_5->setIconSize(ui->pushButton_5->size()); // 设置图标的尺寸
    ui->pushButton_5->setStyleSheet("border:none;background:none;");

    icon=QIcon(":/listCycle.png");
    ui->pushButton_8->setIcon(icon);
    ui->pushButton_8->setIconSize(ui->pushButton_8->size()); // 设置图标的尺寸
    ui->pushButton_8->setStyleSheet("border:none;background:none;");

    icon=QIcon(":/dangqu.png");
    ui->pushButton_7->setIcon(icon);
    ui->pushButton_7->setIconSize(ui->pushButton_7->size()); // 设置图标的尺寸
    ui->pushButton_7->setStyleSheet("border:none;background:none;");
    net=new QNetworkAccessManager(this);
    //net_2=new QNetworkAccessManager(this);

    ui->lineEdit->setPlaceholderText("请输入你要搜索的歌手或者歌曲");
    mod1=new QStandardItemModel(ui->tableView);
    ui->tableView->setModel(mod1);

    QHeaderView *horizontalHeader = ui->tableView->horizontalHeader();
    horizontalHeader->setStyleSheet("QHeaderView::section { background-color: transparent; }");
    connect(net,&QNetworkAccessManager::finished,this,&musicWindow::on_net_finish);
    //connect(net_2,&QNetworkAccessManager::finished,this,&musicWindow::on_net_2_finished);
    player = new QMediaPlayer;
    play_list = new QMediaPlaylist;
    player->setPlaylist(play_list);
    connect(player,&QMediaPlayer::durationChanged,this,&musicWindow::on_slider_duration);
    connect(player,&QMediaPlayer::positionChanged,this,&musicWindow::on_slider_postion);
    sql=new mySql;
}

void musicWindow::backWidget(QWidget *parent)
{
    back=parent;
}

void musicWindow::parseJson(QByteArray json)
{
    player->stop();
    mod1->clear();
    play_list->clear();
    mod1->setHorizontalHeaderLabels({"歌手","歌曲","时长","是否收藏","ID"});
    ui->tableView->setColumnHidden(4,true);
    QString singer;
    QString song;
    int id;
    QString duration;
    QJsonParseError json_error;
    QJsonDocument json_doc=QJsonDocument::fromJson(json,&json_error);
    if(json_error.error==QJsonParseError::NoError)
    {
        if(json_doc.isObject())
        {
            QJsonObject json_object=json_doc.object();
            if(json_object.contains("result"))
            {
                QJsonValue json_value=json_object.value("result");
                if(json_value.isObject())
                {
                    QJsonObject json_object_2=json_value.toObject();
                    if(json_object_2.contains("songs"))
                    {
                        QJsonValue json_value_2=json_object_2.value("songs");
                        if(json_value_2.isArray())
                        {
                            QJsonArray json_array=json_value_2.toArray();
                            int songSize=json_array.size();
                            qDebug()<<songSize;
                            for(int i=0;i<songSize;i++)
                            {
                                QJsonValue json_value_3=json_array.at(i);
                                if(json_value_3.isObject())
                                {
                                    QJsonObject json_object_3=json_value_3.toObject();
                                    if(json_object_3.contains("id"))
                                    {
                                        QJsonValue json_value_8=json_object_3.value("id");
                                        if(!json_value_8.isNull())
                                        {
                                            id=json_value_8.toInt();
                                        }
                                    }
                                    if(json_object_3.contains("name"))
                                    {
                                        QJsonValue json_value_4=json_object_3.value("name");
                                        if(json_value_4.isString())
                                        {
                                            song=json_value_4.toString();
                                        }
                                    }
                                    if(json_object_3.contains("duration"))
                                    {
                                        QJsonValue json_value_10=json_object_3.value("duration");
                                        if(!json_value_10.isNull())
                                        {
                                            int temp=json_value_10.toInt();
                                            int minute=temp/60000;
                                            int second=(temp%60000)/1000;
                                            duration=QString("%1:%2").arg(minute,2,10,QChar('0')).arg(second,2,10,QChar('0'));
                                        }
                                    }
                                    if(json_object_3.contains("artists"))
                                    {
                                        QJsonValue json_value_5=json_object_3.value("artists");
                                        if(json_value_5.isArray())
                                        {
                                            QJsonArray json_array_2=json_value_5.toArray();
                                            for(int j=0;j<json_array_2.size();j++)
                                            {
                                                QJsonValue json_value_6=json_array_2.at(j);
                                                if(json_value_6.isObject())
                                                {
                                                    QJsonObject json_object_4=json_value_6.toObject();
                                                    if(json_object_4.contains("name"))
                                                    {
                                                        QJsonValue json_value_7=json_object_4.value("name");
                                                        if(json_value_7.isString())
                                                        {
                                                            if(j==0)
                                                            {
                                                                singer=json_value_7.toString();
                                                            }
                                                            else
                                                            {
                                                                singer+=QString("/")+json_value_7.toString();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                mod1->setItem(i,0,new QStandardItem(singer));
                                mod1->setItem(i,1,new QStandardItem(song));
                                mod1->setItem(i,2,new QStandardItem(duration));
                                QString command=QString("SELECT * FROM collectedSongs WHERE id=%1").arg(id);
                                if(sql->isCollected(command))
                                {
                                    mod1->setItem(i,3,new QStandardItem(QIcon(":/collected.png"),"已收藏"));
                                }
                                else
                                {
                                    mod1->setItem(i,3,new QStandardItem(QIcon(":/nocollected.png"),"收藏"));
                                }
                                mod1->setItem(i,4,new QStandardItem(QString::number(id)));
                                QString playUrl = "http://music.163.com/song/media/outer/url?id=";
                                playUrl+=QString::number(id);
                                playUrl+=".mp3";
                                qDebug()<<playUrl;
                                play_list->addMedia(QUrl(playUrl));
                            }
                        }

                    }
                }
            }
        }
    }
    else
    {
        qDebug()<<json_error.errorString();
    }
}

void musicWindow::on_net_finish(QNetworkReply *reply)
{
    int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(status!=200)
    {
        qDebug("网络连接错误");
        return;
    }
    else
    {
        QByteArray json=reply->readAll();
        parseJson(json);
    }
}

//void musicWindow::on_net_2_finished(QNetworkReply *reply)
//{
//    int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
//    if(status!=200)
//    {
//        qDebug("网络连接错误");
//        return;
//    }
//    else
//    {
//        QByteArray json=reply->readAll();
//        qDebug()<<(QString)json;
//    }
//}

musicWindow::~musicWindow()
{
    delete ui;
}

void musicWindow::on_pushButton_clicked()
{
    QString data=ui->lineEdit->text();
    QString address = "http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=";
    address+=data;
    address += "&type=1&offset=0&total=true&limit=10";
    net->get(QNetworkRequest(QUrl(address)));
}

void musicWindow::on_tableView_doubleClicked(const QModelIndex &index)
{
    qDebug()<<index.row();
    play_list->setCurrentIndex(index.row());
    player->setVolume(100);
    player->play();
//    QString id="1299550532";
//    QString address=QString("https://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(id);
//    net_2->get(QNetworkRequest(QUrl(address)));
}

void musicWindow::on_pushButton_2_clicked()
{
    player->stop();
    mod1->clear();
    play_list->clear();
    ui->lineEdit->clear();
    ui->pushButton_7->setStyleSheet("border:none;background:none;");
    ui->pushButton_8->setStyleSheet("border:none;background:none;");
    back->show();
    this->hide();
}

void musicWindow::on_pushButton_3_clicked()
{
    if(play_list->currentIndex()>0)
    {
        play_list->previous();
        player->play();
    }
}

void musicWindow::on_pushButton_5_clicked()
{
    if(play_list->currentIndex()<play_list->mediaCount()-1)
    {
        play_list->next();
        player->play();
    }
}

void musicWindow::on_pushButton_4_clicked()
{
    clicks=(clicks+1)%2;
    if(clicks==1)
    {
        player->pause();
    }
    if(clicks==0)
    {
        player->play();
    }
}

void musicWindow::on_slider_duration(int duration)
{
    ui->horizontalSlider->setValue(0);
    ui->horizontalSlider->setRange(0,duration);
    int minute=duration/60000;
    int second=(duration%60000)/1000;
    QString end=QString("%1:%2").arg(minute,2,10,QChar('0')).arg(second,2,10,QChar('0'));
    ui->label_3->setText(end);
}

void musicWindow::on_slider_postion(int position)
{
    ui->horizontalSlider->setValue(position);
    int minute=position/60000;
    int second=(position%60000)/1000;
    QString begin=QString("%1:%2").arg(minute,2,10,QChar('0')).arg(second,2,10,QChar('0'));
    ui->label_2->setText(begin);
}

void musicWindow::on_horizontalSlider_sliderReleased()
{
    player->setPosition(ui->horizontalSlider->value());
}

void musicWindow::on_tableView_clicked(const QModelIndex &index)
{
    if(index.column()==3)
    {
        if(mod1->item(index.row(),index.column())->text()=="收藏")
        {
            //收藏
            QString singer=mod1->item(index.row(),0)->text();
            QString song=mod1->item(index.row(),1)->text();
            QString duration=mod1->item(index.row(),2)->text();
            QString id=mod1->item(index.row(),4)->text();
            if(sql->openBase())
            {
                mod1->setItem(index.row(),index.column(),new QStandardItem(QIcon(":/collected.png"),"已收藏"));
                QString command_1=QString("CREATE TABLE IF NOT EXISTS collectedSongs(\
                                          singer TEXT,\
                                          song TEXT,\
                                          duration TEXT,\
                                          id TEXT)");
                        sql->commonFuc(command_1);
                command_1=QString("INSERT INTO collectedSongs VALUES('%1','%2','%3','%4')")\
                        .arg(singer)\
                        .arg(song)\
                        .arg(duration)\
                        .arg(id);
                sql->commonFuc(command_1);
                sql->closeBase();
            }
            else
            {
                qDebug()<<"open dataBase fail";
            }
        }
        else//取消收藏
        {
            if(sql->openBase())
            {
               QString id=mod1->item(index.row(),4)->text();
               QString command=QString("DELETE FROM collectedSongs WHERE id='%1'").arg(id);
               sql->commonFuc(command);
               mod1->setItem(index.row(),index.column(),new QStandardItem(QIcon(":/nocollected.png"),"收藏"));
               sql->closeBase();
            }
        }
    }
}

void musicWindow::on_pushButton_6_clicked()
{
    //收藏歌单
    player->stop();
    mod1->clear();
    play_list->clear();
    ui->lineEdit->clear();
    ui->pushButton_7->setStyleSheet("border:none;background:none;");
    ui->pushButton_8->setStyleSheet("border:none;background:none;");
    mod1->setHorizontalHeaderLabels({"歌手","歌曲","时长","是否收藏","ID"});
    ui->tableView->setColumnHidden(4,true);
    sql->openBase();
    QString command=QString("SELECT * FROM collectedSongs");
    QSqlQuery query;
    if(!query.exec(command))
    {
        qDebug()<<"error:"<<query.lastError();
    }
    else
    {
        int i=0;
        while(query.next())
        {
            QString singer=query.value(0).toString();
            QString song=query.value(1).toString();
            QString duration=query.value(2).toString();
            QString id=query.value(3).toString();
            QString playUrl = "http://music.163.com/song/media/outer/url?id=";
            playUrl+=id;
            playUrl+=".mp3";
            qDebug()<<playUrl;
            play_list->addMedia(QUrl(playUrl));
            mod1->setItem(i,0,new QStandardItem(singer));
            mod1->setItem(i,1,new QStandardItem(song));
            mod1->setItem(i,2,new QStandardItem(duration));
            mod1->setItem(i,3,new QStandardItem(QIcon(":/collected.png"),"已收藏"));
            mod1->setItem(i,4,new QStandardItem(id));
            i++;
        }
    }
    sql->closeBase();
}


void musicWindow::on_pushButton_7_clicked()
{
    qDebug("单曲循环");
    dangqu=(dangqu+1)%2;
    if(dangqu==1)
    {
    ui->pushButton_7->setStyleSheet("border: 2px dashed #FFC0CB;");
    ui->pushButton_8->setStyleSheet("border:none;background:none;");
    play_list->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else
    {
         ui->pushButton_7->setStyleSheet("border:none;background:none;");
         play_list->setPlaybackMode(QMediaPlaylist::Sequential);
    }
}

void musicWindow::on_pushButton_8_clicked()
{
    qDebug("列表循环播放");
    listcycle=(listcycle+1)%2;
    if(listcycle==1)
    {
    ui->pushButton_8->setStyleSheet("border: 2px dashed #FFC0CB;");
    ui->pushButton_7->setStyleSheet("border:none;background:none;");
    play_list->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
    {
         ui->pushButton_8->setStyleSheet("border:none;background:none;");
         play_list->setPlaybackMode(QMediaPlaylist::Sequential);
    }
}
